from rest_framework import serializers, exceptions
from rest_framework.response import Response

from storage.models import User, File, Access
from storage.utils import generate_random_string
from CloudStorage4.settings import SERVER_HOST

class RegisterSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True)
    first_name = serializers.CharField(max_length=255)
    last_name = serializers.CharField(max_length=255)

    def validate(self, attrs):
        email = attrs.get('email')

        if User.objects.filter(email=email).exists():
            raise serializers.ValidationError({'email': 'This email already taken.'})

        return attrs

    def create(self, validated_data):
        validated_data['username'] = validated_data['email']
        user = User.objects.create_user(**validated_data)
        return user



class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True)

    def create(self, validated_data):
        email = validated_data.get('email')
        password = validated_data.get('password')
        if User.objects.filter(email=email).exists():
            if User.objects.get(email=email).check_password(password):
                return {'success': True, 'message': (User.objects.get(email=email)) }



        return {
            'success': False,
            'message': 'Login Failed'
        }


class FileUploadSerializer(serializers.Serializer):
    files = serializers.ListField(child=serializers.FileField())

    def create(self, validated_data):
        user = validated_data.pop('user')
        response = []
        userFiles_name = []

        for ac in Access.objects.filter(user=user, isOwner=True).all():
            userFiles_name.append(ac.file.file_name)

        for file in validated_data['files']:

            extension = file.name.split('.')[-1]

            if extension not in ['doc', 'pdf', 'docx', 'zip', 'jpeg', 'jpg', 'png']:
                response.append({
                    'success': False,
                    'message': 'File not loaded',
                    'name': file.name
                })
                continue

            if file.size/1024/1024 > 2:
                response.append({
                    'success': False,
                    'message': 'File not loaded',
                    'name': file.name
                })
                continue


            customname = file.name
            i = 1

            print(userFiles_name)
            while customname in userFiles_name:
                customname = file.name
                customname = customname.replace(f".{extension}", '')
                customname = f"{customname} ({i}).{extension}"
                i+=1


            file_id = generate_random_string(10)

            file.name = generate_random_string(20)

            response.append({
                 "success": True,
                 "message": "Success",
                 "name": customname,
                 "url": f"{SERVER_HOST}/files/{file_id}",
                 "file_id": file_id
                }),

            newfile = File.objects.create(file=file, file_id=file_id, file_name=customname)
            access = Access.objects.create(user=user, file=newfile, isOwner=True)

        return response


class FileRenameSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=255)
    file_id = serializers.CharField(max_length=10)

    def create(self, validated_data):
        user = validated_data.pop('user')
        file_id = validated_data['file_id']
        name = validated_data['name']

        if user.files.filter(file_name=name).exists():
            raise serializers.ValidationError({'name': 'A file with the same name already exist'})


        file = File.objects.filter(file_id=file_id).first()
        file.file_name = name
        file.save()

        return {
            "success": True,
            "message": "Renamed"
        }

class FileDeleteSerializer(serializers.Serializer):
    file_id = serializers.CharField(max_length=10)

    def create(self, validated_data):
        file_id = validated_data['file_id']
        file = File.objects.filter(file_id=file_id).first()
        file.delete()

        return {
           "success": True,
           "message": "File already deleted"
        }



class FileDownloadSerializer(serializers.Serializer):
    file_id = serializers.CharField(max_length=10)

    def create(self, validated_data):
        file_id = validated_data['file_id']
        file = File.objects.filter(file_id=file_id).first()

        return file


class AddAccessSerializer(serializers.Serializer):
    file_id = serializers.CharField(max_length=10)
    email = serializers.EmailField()

    def create(self, validated_data):
        file_id = validated_data['file_id']

        if not User.objects.filter(email=validated_data['email']).exists():
            raise serializers.ValidationError({'email': 'User does not exist'})

        user = User.objects.filter(email=validated_data['email']).first()
        file = File.objects.filter(file_id=file_id).first()

        if not Access.objects.filter(file=file, user=user).exists():
            Access.objects.create(user=user, file=file)

        response = []
        for ac in Access.objects.filter(file=file).all():
            type = "co-author"
            if ac.isOwner:
                type = "author"

            response.append({
                "fullname": ac.user.get_full_name(),
                "email": ac.user.email,
                "type": type
            })

        return response

class RemoveAccessSerializer(serializers.Serializer):
    file_id = serializers.CharField(max_length=10)
    email = serializers.EmailField()

    def create(self, validated_data):
        file_id = validated_data['file_id']

        if not User.objects.filter(email=validated_data['email']).exists():
            raise serializers.ValidationError({'email': 'User does not exist'})

        user = User.objects.filter(email=validated_data['email']).first()
        file = File.objects.filter(file_id=file_id).first()

        if Access.objects.filter(file=file, user=user).exists():
            if not Access.objects.filter(file=file, user=user, isOwner=True).exists():
                Access.objects.filter(file=file, user=user).delete()

        response = []
        for ac in Access.objects.filter(file=file).all():
            type = "co-author"
            if ac.isOwner:
                type = "author"

            response.append({
                "fullname": ac.user.get_full_name(),
                "email": ac.user.email,
                "type": type
            })

        return response


class AllUserFilesSerializer(serializers.Serializer):
    def create(self, validated_data):
        user = validated_data['user']

        response = []
        for access in Access.objects.filter(user_id=user, isOwner=True).all():
            file = access.file
            accesses = []
            for ac in Access.objects.filter(file=file).all():
                type = "co-author"
                if ac.isOwner:
                    type = "author"

                accesses.append({
                    "fullname": ac.user.get_full_name(),
                    "email": ac.user.email,
                    "type": type
                })

            response.append({
               "file_id": file.file_id,
               "name": file.file_name,
                "url": f"{SERVER_HOST}/files/{file.file_id}",
                "accesses": accesses
            })

        return response


class AllAccessFilesSerializer(serializers.Serializer):
    def create(self, validated_data):
        user = validated_data['user']

        response = []

        for ac in Access.objects.filter(user=user, isOwner=False).all():
            response.append({
                "file_id": ac.file.file_id,
                "name": ac.file.file_name,
                "url": f"{SERVER_HOST}/files/{ac.file.file_id}",
            })

        return response

